package cn.hyatt.code.generator.controller;

import cn.hyatt.code.generator.dto.CodeGeneratorConfig;
import cn.hyatt.code.generator.service.CodeGeneratorService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipOutputStream;

@ResponseBody
@RestController
@AllArgsConstructor
@RequestMapping("base/codeGenerator")
@Tag(name = "代码生成器")
public class CodeGeneratorController {
    private CodeGeneratorService service;

    @PostMapping("/zip")
    private void zip(HttpServletResponse response, @RequestBody CodeGeneratorConfig config) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outputStream), StandardCharsets.UTF_8);
        service.generatorZip(config,zipOutputStream);
        IOUtils.closeQuietly(zipOutputStream);
        byte[] bytes = outputStream.toByteArray();
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
        response.addHeader("Content-Length", "" + bytes.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(bytes, response.getOutputStream());
    }
}
